package com.blindBox.back.dataHandler.dataHandlerImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blindBox.back.commonResult.MsgBackToFront;
import com.blindBox.back.dao_pojo.Paper;
import com.blindBox.back.dao_pojo.Paperchosebywho;
import com.blindBox.back.dataHandler.AbstractDataHandler;
import com.blindBox.back.dataStrategy.PaperGetDataStrategy;
import com.blindBox.back.file.FileManager;
import com.blindBox.back.service.PaperService;
import com.blindBox.back.service.PaperchosebywhoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("paperDataHandler")
public class PaperDataHandler implements AbstractDataHandler<String, MsgBackToFront>
{
     @Resource(name="paperGetDataStrategy")
     private PaperGetDataStrategy paperGetDataStrategy;

     @Autowired
     private PaperService paperService;

     @Autowired
     private PaperchosebywhoService paperchosebywhoService;

     @Autowired
     private FileManager fileManager;

    @Override
    public MsgBackToFront dataHandle(String obj) {
        return paperGetDataStrategy.chose(obj).getPaperDataByChoseStrategy();
    }


    @Override
    public MsgBackToFront dataHandle(String obj, Object[] objs) {
        return paperGetDataStrategy.chose(obj).getPaperDataByChoseStrategy(objs);
    }

    //删除纸条
    public MsgBackToFront delPaperById(Integer p_id)
    {
        //先删除照片
        Paper byId = paperService.getById(p_id);
        boolean ret = fileManager.delTargetFile(byId.getSelfImgs());
        if(!ret) return new MsgBackToFront(null,MsgBackToFront.DEL_FILE_ERROR);

        //先删除paper表
        boolean ret1 = paperService.removeById(p_id);
        //删除映射表
        //删除前，先判断映射表中是否有该纸条的数据
        Paperchosebywho pId = paperchosebywhoService.getOne(new QueryWrapper<Paperchosebywho>().eq("p_id", byId.getId()));
        if(pId==null)
            return ret1?new MsgBackToFront(null,MsgBackToFront.HANDLE_SUCCESS):new MsgBackToFront(null,MsgBackToFront.DATABASE_ERROR);

        boolean ret2 = paperchosebywhoService.remove(new QueryWrapper<Paperchosebywho>().eq("p_id", byId.getId()));
        return (ret1&&ret2)?new MsgBackToFront(null,MsgBackToFront.HANDLE_SUCCESS):new MsgBackToFront(null,MsgBackToFront.DATABASE_ERROR);
    }
}
